package com.mayikt.main.api.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mayikt.common.core.api.BaseApiService;
import com.mayikt.common.core.api.BaseResponse;
import com.mayikt.common.core.utils.IPUtils;
import com.mayikt.common.core.utils.MD5Utils;
import com.mayikt.common.core.utils.RedisUtil;
import com.mayikt.main.api.LoginService;
import com.mayikt.main.api.dto.res.LoginUserReqDto;
import com.mayikt.main.api.impl.entity.SysUser;
import com.mayikt.main.api.impl.entity.SysUserLoginLog;
import com.mayikt.main.api.impl.mapper.SysUserMapper;
import com.mayikt.main.api.impl.producer.LoginProducer;
import com.mayikt.main.api.impl.utils.TokenUtils;
import com.mayikt.main.container.AsyncLogWrappper;
import com.mayikt.main.container.MayiktLogContainer;
import com.mayikt.main.manage.LoginLogManage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 * @author wangjin
 * @title: LoginServiceImpl
 * @projectName mayikt-cloud
 * @description: TODO
 * @date 2022/4/23 0023 17:13
 */

@RestController
@EnableAsync
@Slf4j
public class LoginServiceImpl extends BaseApiService<String> implements LoginService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private LoginLogManage loginLogManage;
    @Autowired
    private LoginProducer loginProducer;

    @Override
    public BaseResponse<String> login(LoginUserReqDto loginUserReqDto) {
        String phoneNumber = loginUserReqDto.getPhoneNumber();
        // 1.验证参数是否为空
        if (StringUtils.isEmpty(phoneNumber)) {
            return setResultError("phoneNumber is null");
        }
        String password = loginUserReqDto.getPassword();
        if (StringUtils.isEmpty(password)) {
            return setResultError("password is null");
        }
        //select * from user where phoneNumber=''
        // 2.根据手机号码查询用户信息
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("phone_number", phoneNumber);
        SysUser sysUser = sysUserMapper.selectOne(sysUserQueryWrapper);
        if (sysUser == null) {
            return setResultError("该手机号码不存在!");
        }
        // 3.获取db存储加密密码
        String dbMd5Password = sysUser.getPassword();
        String userMd5Password = MD5Utils.md5(password + sysUser.getSalt());
        if (!dbMd5Password.equals(userMd5Password)) {
            return setResultError("密码错误!");
        }
        // --------------select * from user where phoneNumber='' and password='password'
        // 4.生成token 存放在redis中 value值=用户userid
        String token = TokenUtils.getToken();
        RedisUtil.setString(token, sysUser.getId() + "");
        JSONObject data = new JSONObject();
        data.put("token", token);
        // 5.登录后续流程
        /**
         * springmvc原理
         * 底层基于servlet封装
         * 调用springmvc封装servlet封装
         * 当前这个方法login 属于同一个线程
         * sysUser.getId(), IPUtils.getIpAddr(request),
         *                 new Date(), token,
         *                 loginUserReqDto.getChannel(), loginUserReqDto.getEquipment()
         */
        // 从当前线程中获取httpservletrequest对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String equipmentName = loginUserReqDto.getEquipment();
        loginUserReqDto.setEquipment(StringUtils.isEmpty(equipmentName) ? null : StringEscapeUtils.escapeHtml(equipmentName));
        // tomcat-nio8080-01
        SysUserLoginLog sysUserLoginLog = new SysUserLoginLog();
        sysUserLoginLog.setUserId(sysUser.getId());
        sysUserLoginLog.setLoginIp(IPUtils.getIpAddr(request));
        sysUserLoginLog.setLoginTime(new Date());
        sysUserLoginLog.setLoginToken(token);
        sysUserLoginLog.setChannel(loginUserReqDto.getChannel());
        sysUserLoginLog.setEquipment(loginUserReqDto.getEquipment());
        sysUserLoginLog.setIsDelete(0);
        log.info("<登录日志:{}>", sysUserLoginLog);

        AsyncLogWrappper asyncLogWrappper = new AsyncLogWrappper(sysUserLoginLog, sysUser);
        //投递对象到队列中
        MayiktLogContainer.addLog(asyncLogWrappper);
        //loginLogManage.asynLoginLog(sysUserLoginLog);
        //使用rabbitmq投递消息
       /* for (int i = 0; i < 10; i++) {
            loginProducer.sendLoginFollowUp(sysUser.getId(), sysUserLoginLog.getLoginIp(), sysUserLoginLog.getLoginTime(),
                    sysUserLoginLog.getLoginToken(), sysUserLoginLog.getChannel(), sysUserLoginLog.getEquipment());

        }*/
        return setResultSuccessData(data.toJSONString());
    }
}
